package com.bygf.curve;

import com.bygf.curve.panel.ChartPanel;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

/**
 * XY曲线，横轴和纵轴都是数值
 *
 * @author sunyupei
 */
public class XYCurve extends Curve {

    //X数值集合
    List<Double> XValueList = new ArrayList<>();
    //Y数值集合
    List<Double> YValueList = new ArrayList<>();

    /**
     * 构造方法
     *
     * @param name
     */
    public XYCurve(String name) {
        this.name = name;
    }

    @Override
    public void valueToPix(ChartPanel chartPanel) {
        XPixList.clear();
        YPixList.clear();
        valueIndex = -1;
        for (int i = 0; i < XValueList.size(); i++) {
            //过滤在当前X轴坐标范围内不会绘制出来的数据，用于节省绘制时间
            if (XValueList.get(i) < chartPanel.getXAxis().getStartValueNow()
                    || XValueList.get(i) > chartPanel.getXAxis().getEndValueNow()) {
                continue;
            }
            double x = chartPanel.getXAxis().valueToPix(XValueList.get(i));
            double y;
            if (isUsedY2Axis()) {
                y = chartPanel.getY2Axis().valueToPix(YValueList.get(i));
            } else {
                y = chartPanel.getYAxis().valueToPix(YValueList.get(i));
            }
            XPixList.add(x);
            YPixList.add(y);
            if (valueIndex == -1) {
                valueIndex = i;
            }
        }
    }

    /**
     * 往曲线中增加数值
     *
     * @param xValue
     * @param yValue
     */
    public void addItem(double xValue, double yValue) {
        XValueList.add(xValue);
        YValueList.add(yValue);
    }

    @Override
    public String getToolTip(Point point) {
        for (int i = 0; i < XPixList.size(); i++) {
            Point2D pointTemp = new Point2D.Double(XPixList.get(i), YPixList.get(i));
            if (pointTemp.distance(point) < getRender().getStroke().getLineWidth() * 2) {
                ArrayList list = new ArrayList();
                list.add(name);
                list.add(XValueList.get(i + valueIndex));
                list.add(YValueList.get(i + valueIndex));
                return toolTipFormat.format(list);
            }
        }
        return null;
    }
}
